package peer.view;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.table.DefaultTableModel;

public class TableUtil {
	/**
	 * @author Silvio Vilerino
	 * @param vecData ArrayList containing Objects inside. Table will show every object as a row with all its fields displayed on it.
	 * @return
	 */
	public static DefaultTableModel parseGenericResponse(ArrayList<Object> vecData){
		Vector<Vector<String>> tableData=new Vector<Vector<String>>();
		Vector<String> tableCols=new Vector<String>();
		if(vecData.size()>0){
			Field[] fields= vecData.get(0).getClass().getDeclaredFields();
			for(Field campo : fields){
				campo.setAccessible(true);
				tableCols.add(campo.getName());
			}
			for(Object objectItem : vecData){
				Vector<String> subData=new Vector<String>();
				for(Field campo : fields){
					campo.setAccessible(true);
					Object fieldValue = null;
					try {
						fieldValue = campo.get(objectItem);
						if(fieldValue!=null){
							subData.add(fieldValue.toString());
						}else{
							subData.add("(NULL)");
						}
					} catch (IllegalArgumentException e) {
						e.printStackTrace(System.err);
					} catch (IllegalAccessException e) {
						e.printStackTrace(System.err);
					}
				}
				tableData.add(subData);
			}
		}
		return new DefaultTableModel(tableData, tableCols);
	}


}
